package com.qipay.api.wx.controller.v1;

import com.alipay.api.domain.DataEntry;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qipay.api.wx.controller.v1.vo.CpPayWeiXinMpPayGetOpenIdVo;
import com.qipay.baas.model.Order;
import com.qipay.order.config.OrderStateEnum;
import com.qipay.order.service.OrderService;
import com.qipay.pay.WeiXinMpPayService;
import com.qipay.pay.WeiXinPayService;
import com.qipay.pay.entity.SpPayWeiXinNativeCallbackRequest;
import com.qipay.scalar.type.ApiStatusEnum;
import com.qipay.sp.SpConfigService;
import com.qipay.utils.RequestUtils;
import com.qipay.utils.ResultUtils;
import com.qipay.utils.SignSortMD5Utils;
import com.qipay.utils.XmlUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.MessageDigest;
import java.util.*;

@RestController
@RequestMapping("/callback/v1/wx")
public class WxCallbackController {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    private static final String SIGN_KEY="sign";
    private static final String SP_CONFIG_KEY_SECRET="key";

    @Autowired
    WeiXinMpPayService weiXinMpPayService;
    @Autowired
    OrderService orderService;
    @Autowired
    SpConfigService spConfigService;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    WeiXinPayService weiXinPayService;

    @Value("${api.mp.pay.spconfig.secret.key}")
    String apiMpPaySpconfigSecretKey;

    @Value("${api.mp.pay.spconfig.appid.key}")
    String apiMpPaySpconfigAppIdKey;

    @RequestMapping(value = "/sp/openid", method = RequestMethod.GET, produces = {"application/xml;charset=UTF-8"})
    private ModelAndView unionCreate(
            HttpServletRequest request,
            @RequestParam("code") String code,
            @RequestParam("state") Long orderId,
            HttpServletResponse response
    ) throws Exception {

        Order order = orderService.get(orderId);
        Assert.notNull(order, "错误的订单信息");
        Assert.isTrue(Objects.equals(order.getState(), OrderStateEnum.NOTPAY.getType()),
                ResultUtils.buildErrorMsg(ApiStatusEnum.ARGUMENT_ERR,"错误的订单信息"));

        String appid = spConfigService.getValue(order.getSpId(), apiMpPaySpconfigAppIdKey);
        Assert.notNull(appid,
                "未配置sp的appid");
        String secret = spConfigService.getValue(order.getSpId(), apiMpPaySpconfigSecretKey);
        Assert.notNull(secret,
                "未配置sp的secret");

        String url = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                appid, secret, code);

        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(httpGet);

        Assert.isTrue(httpResponse.getStatusLine().getStatusCode() == 200,
                ResultUtils.buildErrorMsg(ApiStatusEnum.SERVICE_ERR,"请求微信接口获取openid出错"));

        HttpEntity entity = httpResponse.getEntity();
        String responseStr = EntityUtils.toString(entity, "utf-8");
        logger.info("响应：{}",responseStr);
        CpPayWeiXinMpPayGetOpenIdVo cpPayWeiXinMpPayGetOpenIdVo =
                objectMapper.readValue(responseStr, CpPayWeiXinMpPayGetOpenIdVo.class);

        Assert.notNull(cpPayWeiXinMpPayGetOpenIdVo.getOpenid(),
                ResultUtils.buildErrorMsg(ApiStatusEnum.SERVICE_ERR,"请求微信接口获取openid出错, openid为null"));

        Map<String, Object> pay_infoMap = weiXinMpPayService.jspay(orderId, cpPayWeiXinMpPayGetOpenIdVo.getOpenid());

        Assert.notNull(pay_infoMap,
                ResultUtils.buildErrorMsg(ApiStatusEnum.SERVICE_ERR,"请求sp的公众号支付失败"));

        SortedMap<String, String> finalpackage = new TreeMap<String, String>();
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String nonceStr2 = pay_infoMap.get("nonce_str").toString();
        String prepay_id2 = "prepay_id=" + pay_infoMap.get("prepay_id").toString();
        String packages = prepay_id2;
        String appId = pay_infoMap.get("appid").toString();
        String key  =  pay_infoMap.get("key").toString();

        finalpackage.put("appId", appId);
        finalpackage.put("timeStamp", timestamp);
        finalpackage.put("nonceStr", nonceStr2);
        finalpackage.put("package", packages);
        finalpackage.put("signType", "MD5");

        StringBuffer sb = new StringBuffer();
        Set es = finalpackage.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k)
                    && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + key);
        String finalsign = MD5Encode(sb.toString(), "UTF-8").toUpperCase();

        ModelAndView modelAndView = new ModelAndView("/pay/mp_script");
        modelAndView.addObject("appid", pay_infoMap.get("appid").toString());
        modelAndView.addObject("timeStamp",timestamp);
        modelAndView.addObject("nonceStr",nonceStr2);
        modelAndView.addObject("packageValue",packages);
        modelAndView.addObject("paySign",finalsign);

        return modelAndView;
    }
    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            else
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
        } catch (Exception exception) {
        }
        return resultString;
    }
    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
    @RequestMapping(value = "/wap", method = RequestMethod.POST, produces = {"application/xml;charset=UTF-8"})
    private String unionCreate(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        String xml = RequestUtils.getRequestBody(request);
        logger.info("request from " + request.getRequestURI() + ", request body:" + xml);

        Map<String, Object> params = XmlUtils.toMap(xml);

        if(!"SUCCESS".equals(params.get("return_code"))) {
            logger.error("微信支付回调return_code错误" + params);
            return "FAIL";
        }

        SpPayWeiXinNativeCallbackRequest bean = convertToBean(params);

        Order order = orderService.getByTradeNo(bean.getOutTradeNo());
        if(order == null){
            return "FAIL";
        }

        String secret = spConfigService.getValue(order.getSpId(),WxCallbackController.SP_CONFIG_KEY_SECRET);
        String fromSig = params.get(WxCallbackController.SIGN_KEY).toString();
        String mySig = SignSortMD5Utils.getSign(params, secret, WxCallbackController.SIGN_KEY);
        if (!StringUtils.equalsIgnoreCase(fromSig, mySig)) {
            logger.warn("签名不一致:fromSig:" + fromSig + ", mysig:" + mySig);
            return "FAIL";
        }

        try {
            weiXinPayService.payWeixinNativeCallback(bean);
            return "SUCCESS";
        }catch (Exception ex) {
            logger.error("回调报错:" +  XmlUtils.toString(params, "xml"));
        }
        return "FAIL";
    }

    private SpPayWeiXinNativeCallbackRequest convertToBean(Map<String, Object> params) {
        SpPayWeiXinNativeCallbackRequest request = new SpPayWeiXinNativeCallbackRequest();
        if("SUCCESS".equals(params.get("return_code"))) {
            request.setStatus(0);
        } else {
            request.setStatus(1);
        }

        if("SUCCESS".equals(params.get("result_code"))) {
            request.setResultCode(0);
            request.setPayResult(0);
        }else{
            request.setResultCode(1);
            request.setPayResult(1);
        }

        if(params.get("mch_id") != null) {
            request.setMchId(params.get("mch_id").toString());
        }

        if(params.get("nonce_str") != null) {
            request.setNonceStr(params.get("nonce_str").toString());
        }

        if(params.get("sign") != null) {
            request.setSign(params.get("sign").toString());
        }

        if(params.get("transaction_id") != null) {
            request.setTransactionId(params.get("transaction_id").toString());
        }

        if(params.get("out_trade_no") != null) {
            request.setOutTradeNo(params.get("out_trade_no").toString());
        }

        if(params.get("time_end") != null) {
            request.setTimeEnd(params.get("time_end").toString());
        }

        if(params.get("total_fee") != null) {
            request.setTotalFee(Integer.valueOf(params.get("total_fee").toString()));
        }

        if(params.get("out_transaction_id") != null) {
            request.setOutTransactionId(params.get("out_transaction_id").toString());
        }

        if(params.get("fee_type") != null) {
            request.setFeeType(params.get("fee_type").toString());
        }

        return request;
    }
}
